import { _decorator, Component, Node, instantiate, Prefab } from 'cc';
import { PlayerController } from './PlayerController';
import { Label } from 'cc';

const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {

    @property({type: PlayerController})
    public player: PlayerController | null = null;

    @property({type: Label})
    public stepLabel: Label  = null;

    @property
    public roadLength:number = 50;
    private _road: number[] =[0];

    @property({type: Prefab})
    public cubePrfb: Prefab | null = null;

    start() {
        this.genrateRoad();
        this.player?.node.on("JumpEnd",this.onPlayerJumpEnd,this);
    }

    genrateRoad() {
        this.node.removeAllChildren();

        this._road=[0];
        this._road[0] = 1;
        this._road[1] = Math.floor(Math.random()*2);
        this._road[2] = Math.floor(Math.random()*2);

        for(let i = 3; i < this.roadLength; i++) {
            if(this._road[i-2] && this._road[i-1] === 0) {
                this._road[i]=1;
            } else {
                this._road[i] = Math.floor(Math.random()*2);
            }
           
        }

        for(let i = 0; i < this.roadLength; i++) {
            if(this._road[i] === 1){
                let block: Node | null = null;
                block = instantiate(this.cubePrfb);
                this.node.addChild(block);
                block.setPosition(i,-1.5,0);
            }
        }
    }

    onPlayerJumpEnd(moveCount: number) {
        this.stepLabel.string = moveCount.toString();
        this.checkResult(moveCount);

    }

    checkResult(moveCount: number) {
        if(moveCount > this.roadLength) {
            console.log("over");
            this.reset();
        } else {
            if(this._road[moveCount] === 0 ) {
                console.log("fail");
            }
        }
        
    }

    reset() {
        this.player.reset();
    }

    update(deltaTime: number) {
        
    }
}


